//  Copyright (c) 2018 Uber Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package pathutils

import (
	"fmt"
	"path"
	"strings"
)

// IsDescendantOfAny returns true if filename is in any ancestor's subtree.
func IsDescendantOfAny(p string, ancestors []string) bool {
	p = AbsPath(p)
	for _, ancestor := range ancestors {
		ancestor = AbsPath(ancestor)
		if p == ancestor || ancestor == "/" ||
			strings.HasPrefix(path.Dir(p)+"/", ancestor+"/") {
			return true
		}
	}
	return false
}

// AbsPath fixes leading and trailing slashes of paths for all cases:
// - Layers generated by docker doesn't have leading slashes.
// - Internally generated paths might have leading slashes.
// - Directories have trailing slashes.
// - Files don't have trailing slashes.
func AbsPath(p string) string {
	return path.Join("/", strings.TrimRight(p, "/"))
}

// RelPath removes leading "/".
// Tar headers produced by docker doesn't have leading slashes.
func RelPath(p string) string {
	return strings.TrimLeft(p, "/")
}

// SplitPath trims and splits a path on "/". If the path is "/",
// returns a nil slice.
func SplitPath(p string) []string {
	trimmed := strings.Trim(p, "/")
	if trimmed == "" {
		return nil
	}
	return strings.Split(trimmed, "/")
}

// TrimRoot removes the 'root' path prefix from a path. If the
// prefix is not present, returns an error.
func TrimRoot(p, root string) (string, error) {
	if !strings.HasPrefix(p, root) {
		return "", fmt.Errorf("failed to trim root prefix %s from path %s", root, p)
	}
	return AbsPath(strings.TrimPrefix(p, root)), nil
}
